import wxInit,{getQueryString} from './wxInit.js'
// #ifdef PRIVATE
import {getStoreSphere} from '@/common/request/api'
// #endif
import { useUser,useShoppingCart,useIM } from '@/common/stores';
export const getParams = (key:string) => {
	const queryNameRegex = new RegExp(`[?&]${key}=([^&]*)(?:&|$)`)
	let queryNameMatch = window.location.hash.match(queryNameRegex)
	if(!queryNameMatch){
		queryNameMatch = window.location.search.match(queryNameRegex)
	}
	let params = null
	if(queryNameMatch){
		params = queryNameMatch[1]
		let length = params.length-1
		if(params[length] === '/'){
			params = params.slice(0,length)
		}
	}
	return params
}
 
export default () => {
	if (!uni.getStorageSync('tenant')) {
		uni.redirectTo({
			url:'/pages/404?type=2'
		})
	}
	// #ifdef PRIVATE
	let storeId = uni.getStorageSync('storeId')
	if (storeId) {
		getStoreSphere({ storeId: storeId }).then(res => {
			if ( res.data != 1) {
				uni.redirectTo({
					url:'/pages/404?type=1'
				})
			}
		}).catch(() => {
			uni.redirectTo({
				url:'/pages/404?type=1'
			})
		})
	} else  {
		uni.redirectTo({
			url:'/pages/404?type=1'
		})
	}
	// #endif
	
	let salt = getParams('salt')
	if(salt){
		uni.setStorageSync('userSalt', salt)
	}
	if (uni.getStorageSync('token')) {
		const userStores = useUser()
		const IMStore = useIM()
		// 判断本地是否有缓存的token，有则判断token是否过期
		userStores.getUserInfo().then(res => {
			wxInit(false)
			// IMStore.IMLogin(res)
			useShoppingCart().getCart()
		}).catch(() => {
			wxInit(true)
			uni.removeStorageSync('userInfo')
			uni.removeStorageSync('token')
		})
	} else {
		// 本地没缓存token则判断链接上是否携带了code参数
		wxInit(getQueryString('code') ? true : false)
		uni.removeStorageSync('userInfo')
	}
}
